package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;

public class ChooseUserPhotoDialogFragment extends DialogFragment {
  private static final int REQUEST_CAMERA = 0;
  private static final int REQUEST_ALBUM = 1;
  private static final int REQUEST_CUT = 2;
  private static final int CAMERA = 3;
  public static final String EXTRA_BITMAP = "com.isunland.managesystem.ui.EXTRA_BITMAP";
  public static final String EXTRA_PATH = "com.isunland.managesystem.ui.EXTRA_PATH";
  public static final String EXTRA_BUNDLE = "com.isunland.managesystem.ui.EXTRA_BUNDLE";
  private File mFile;
  private Bitmap mNewBitmap;
  private Bitmap bitmap;
  private String path;

  private AlertDialog mDialog;
  private int[] choiceIds = new int[] {
      R.string.camera, R.string.gallery
  };
  private String[] choiceStrings = new String[choiceIds.length];

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    mDialog = new AlertDialog.Builder(getActivity()).setItems(getChoiceName(), null).create();
    mDialog.setOnShowListener(new OnShowListener() {

      @Override public void onShow(DialogInterface dialog) {
        ListView lv = mDialog.getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {

              //						拍照
              case 0:
                //							if (Build.VERSION.SDK_INT > 23) {
                //								int checkCamera = ContextCompat.checkSelfPermission(getActivity(),
                //										Manifest.permission.CAMERA);
                //								if (checkCamera != PackageManager.PERMISSION_GRANTED) {
                //									ActivityCompat.requestPermissions(getActivity(),
                //											new String[] { Manifest.permission.CAMERA }, CAMERA);
                //								}
                //								takePhoto();
                //							}else{
                takePhoto();
                //							}
                break;
              //图库
              case 1:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, REQUEST_ALBUM);
                break;

              default:
                break;
              //
            }
          }
        });
      }
    });

    return mDialog;
  }

  protected void takePhoto() {
    if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

      mFile = new File(FileUtil.getFileDir(), System.currentTimeMillis() + ".jpg");

      mFile.getParentFile().mkdirs();
      Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
      startActivityForResult(intent2, REQUEST_CAMERA);
    } else {
      Toast.makeText(getActivity(), R.string.check_sd_card, Toast.LENGTH_SHORT).show();
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      if (mDialog != null && mDialog.isShowing()) {
        mDialog.dismiss();
      }

      return;
    }
    switch (requestCode) {
      case REQUEST_CAMERA:

        //不裁剪
        //			mFile=compress(mFile.getAbsolutePath());

        //裁剪
        Uri takeUri = Uri.fromFile(mFile);
        Log.i("camera.uri=", takeUri + "");
        //			path =mFile.getAbsolutePath();
        startPhotoZoom(takeUri);
        break;
      case REQUEST_ALBUM:
        //不裁剪
        //			Uri uri=data.getData();
        //			String path = FileUtil.getPath(getActivity(), uri);
        //			mFile = compress(path);
        //			LogUtil.i(path);

        //裁剪
        Uri uri = data.getData();
        path = FileUtil.getPath(getActivity(), uri);
        startPhotoZoom(uri);
        break;
      //裁剪
      case REQUEST_CUT:// 返回的结果
        Bundle bundle = data.getExtras();
        if (bundle != null) {
          bitmap = bundle.getParcelable("data");
        }

        mNewBitmap = ImageTools.zoomBitmap(bitmap, 400, 400);
        bitmap.recycle();
        mFile = ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
            System.currentTimeMillis() + "");
        Log.i("mFile=", mFile + "");
        if (null == mFile) {
          Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
          mDialog.dismiss();
          return;
        }
        setResult(mFile.getAbsolutePath());
        mDialog.dismiss();
        break;
      default:
        break;
    }
    //		if (null==mFile) {
    //		Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
    //		mDialog.dismiss();
    //		return;
    //	}
    //		setResult(mFile.getAbsolutePath());
    //		mDialog.dismiss();
    //
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 压缩图片
   */
  private File compress(String path) {
    bitmap = BitmapFactory.decodeFile(path);
    if (bitmap == null) {
      Toast.makeText(getActivity(), "bitmap==null", Toast.LENGTH_SHORT).show();
      return null;
    }
    mNewBitmap = ImageTools.zoomBitmap(bitmap, 400, 400);
    bitmap.recycle();
    return ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
        System.currentTimeMillis() + "");
  }

  private void setResult(String absolutePath) {
    if (getTargetFragment() == null) return;
    Intent i = new Intent();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mNewBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] bitmapByte = baos.toByteArray();
    i.putExtra(EXTRA_BITMAP, bitmapByte);

    i.putExtra(EXTRA_PATH, absolutePath);//图片地址

    LogUtil.i(absolutePath);

    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
  }

  //调用系统裁剪
  private void startPhotoZoom(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    // crop为true是设置在开启的intent中设置显示的view可以剪裁
    intent.putExtra("crop", "true");

    // aspectX aspectY 是宽高的比例
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);

    // outputX,outputY 是剪裁图片的宽高
    intent.putExtra("outputX", 300);
    intent.putExtra("outputY", 300);
    intent.putExtra("return-data", true);
    intent.putExtra("noFaceDetection", true);
    startActivityForResult(intent, REQUEST_CUT);
  }

  private String[] getChoiceName() {
    for (int i = 0; i < choiceIds.length; i++) {

      choiceStrings[i] = getResources().getString(choiceIds[i]);
    }

    return choiceStrings;
  }
}
